package com.yljk.yljkproject;

import static com.yilijk.base.utils.DevicesUtils.DEVICES_UUID;
import static com.yilijk.base.utils.DevicesUtils.getUUID;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.BV.LinearGradient.LinearGradientManager;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alsk.rn.common.basic.RNReactModulesPackage;
import com.alsk.rn.common.init.RNInitInterface;
import com.alsk.rn.common.network.request.RequestListener;
import com.alsk.rn.common.plugin.PluginInformation;
import com.alsk.rn.kit.RNKitManager;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.huawei.agconnect.crash.AGConnectCrash;
import com.reactnativecommunity.webview.RNCWebViewManager;
import com.reactnativecommunity.webview.RNCWebViewModule;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yilijk.base.AppBase;
import com.yilijk.base.constants.UserInfo;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.core.NetWorkService;
import com.yilijk.base.network.core.RetrofitManager;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.NetAttestationUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.SdkConfigApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.oldbase.ModulesBaseApp;
import com.yljk.yljkproject.utils.SearchSpUtils;
import com.yljk.yljkproject.utils.ThreeSDKInitUtils;
import com.yljk.yljkproject.utils.ThreeSDKUtils;
import com.yljk.yljkproject.utils.UmengUtils;
import com.yljk.yljkproject.entity.RNHostBean;
import com.yljk.yljkproject.rnmodule.RNKitImModule;
import com.yljk.yljkproject.rnmodule.RNNetworkModule;
import com.yljk.yljkproject.rnmodule.RNRouterModule;
import com.yljk.yljkproject.utils.ReactUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import me.jessyan.autosize.AutoSizeConfig;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//import com.example.imkefu.KefuImHelper;


public class MyApplication extends ModulesBaseApp {

    public static boolean homeType = true;  //true 代表 rn跳首页

    private static MyApplication myApplication;

    public static MyApplication getMyApplication() {
        return myApplication;
    }

    public static int LocalDominNo = 4;

    private String token = "";
    private String mobile = "";

    private boolean UserAgreeChecked = false;

    @Override
    public void onCreateModuleApp(Application application) {
        myApplication = this;
        AppBase.init(application);
        AppBase.setEnable(BuildConfig.OPEN_LOG);
        LocalDominNo = BuildConfig.DOMIN_NO;


//        DevicesUtils.init(this);//设备单例初始化
        String spVersionCode = "";
        try {
            spVersionCode = SharedPreferencesUtils.getInstance().getUment_String("versionCode", "").trim();
        } catch (Throwable throwable) {
            // spVersionCode = ""
        }
        ALog.e("oakkk", "this version: " + spVersionCode);
        if (!TextUtils.isEmpty(spVersionCode)) {
            int versionCode = 0;
            try {
                versionCode = Integer.parseInt(spVersionCode);
            } catch (Throwable throwable) {
//                versionCode = 0;
            }
            if (versionCode < 20002) {
                SharedPreferencesUtils.getInstance().removeAll(this);
                SharedPreferencesUtils.getInstance().removePopAll(this);
                SharedPreferencesUtils.getInstance().removeUmeng();
            }
        } else {
            SharedPreferencesUtils.getInstance().removeAll(this);
            SharedPreferencesUtils.getInstance().removePopAll(this);
            SharedPreferencesUtils.getInstance().removeUmeng();
        }
        SharedPreferencesUtils.getInstance().saveUment("versionCode", DevicesUtils.getVersionCode() + "");
        SharedPreferencesUtils.getInstance().saveUment("versionName", DevicesUtils.getVersionName() + "");


        token = SharedPreferencesUtils.getInstance().getString(UserInfo.token, null);
        mobile = SharedPreferencesUtils.getInstance().getString(UserInfo.mobile, null);
        initUUID();
//        NetAttestationUtils.getInstance().setSALT("");

        RNKitInit(application);//rikit
        initUmeng();//Ument
        initThreeSDK();
        ARouterInit(this);//ARouter
        AutoSizeInit();//屏幕适配（今日头条）
        WechatInit();
        SearchSpUtils.initSpUtils(this);
    }

    private void initUUID() {
        setUserAgreeChecked(false);
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(mobile)) {
            setUserAgreeChecked(true);
        }

        DEVICES_UUID = SharedPreferencesUtils.getInstance().getUment_String("sp_uuid", "");
        if (TextUtils.isEmpty(DEVICES_UUID)) {
            DEVICES_UUID = getUUID(this);
            NetAttestationUtils.getInstance().setSALT("");
            SharedPreferencesUtils.getInstance().saveUment("sp_uuid", DEVICES_UUID);
        }
    }

    private void initThreeSDK() {
        StatService.setAuthorizedState(this, false);
        ThreeSDKInitUtils.getInstance().setIsInitialized(false);
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(mobile)) {
            ALog.e("oakkk", "init three SDK Application!");
            ThreeSDKInitUtils.getInstance().init(this);
        }
    }

    @Override
    public void onTerminate() {
        ClickUtils.sendEvent("app_onclose", this, "APP关闭");
        super.onTerminate();
    }


    //请求动态域名
    public String domain;


    public static IWXAPI iwxapi;

    private void WechatInit() {
        iwxapi = WXAPIFactory.createWXAPI(this, SdkConfigApi.WeChat.Id);
        iwxapi.registerApp(SdkConfigApi.WeChat.Id);
    }

//    private void YWQInit() {
//        /**
//         * 医网签环境设置
//         * EnvType.PUBLIC为医网信正式环境
//         * EnvType.INTEGRATE为集成环境
//         */
//        //医网签 接口设置
//
//    }

//    /**
//     * IM客服云
//     * Appkey：1431210104025974#kefuchannelapp87083
//     * tenantId：87083
//     * IM服务号：kefuchannelimid_571561
//     */
//    private void IMCustomerServiceInit() {
//
//    }

    //屏幕适配
    private void AutoSizeInit() {
        //今日头条屏幕适配
        AutoSizeConfig.getInstance()
                .setDesignWidthInDp(375)
                .setDesignHeightInDp(863);
    }

    //rn
    private void RNKitInit(Application application) {

        RNReactModulesPackage.registerViewManager(RNCWebViewManager.class);
        RNReactModulesPackage.registerNativeModule(RNCWebViewModule.class);
        RNReactModulesPackage.registerViewManager(LinearGradientManager.class);

        ReactUtils.INSTANCE.createIgnoreVerifySSL("TLSv1.1");
        RNKitManager.INSTANCE.kitInit(new RNInitInterface() {
            @Override
            public Application getContext() {
                return MyApplication.this;
            }

            @Override
            public String getDownloadUrl() {
                return "";
            }

            @Override
            public String getAppId() {
                return "2";
            }

            @Override
            public boolean isTestEnv() {
                return com.yilijk.base.utils.DevicesUtils.isEnvironment();
            }

            @Override
            public void requestPluginInfo(Context context, RequestListener<List<PluginInformation>> requestListener) {
                if (ConfigApi.Open.isRnUpdata) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("appid", 2);
                        jsonObject.put("version", 20000);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonObject.toString());
                    Call<ResponseBody> call = RetrofitManager
                            .getRetrofitManager()
                            .getRetrofit()
                            .create(NetWorkService.class)
                            .post(DevicesUtils.isEnvironment() ? UrlApi.POST.updataRnJsBundle_t2 : UrlApi.POST.updataRnJsBundle_api, requestBody);
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response != null && response.body() != null) {
                                if (!TextUtils.isEmpty(response.body().toString())) {
                                    try {
                                        String result = response.body().string();
                                        RNHostBean rnHostBean = new Gson().fromJson(result, RNHostBean.class);
                                        if (rnHostBean.getCode() == 200) {
                                            List<PluginInformation> data = rnHostBean.getData();
                                            requestListener.onSuccess(data);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
//                    RequestParams params = new RequestParams();
//                    params.put("appid", 2);
//                    params.put("version", 20000);//DevicesUtils.getVersion());
//                    HttpUtils.post(DevicesUtils.isEnvironment() ? UrlApi.POST.updataRnJsBundle_d1 : UrlApi.POST.updataRnJsBundle_api, params, new HttpCallBack<RNHostBean>() {
//                        @Override
//                        public void onSuccess(RNHostBean rnHostBean, int code) {
//                            if (rnHostBean.getCode() == 200) {
//                                List<PluginInformation> data = rnHostBean.getData();
//                                requestListener.onSuccess(data);
//                            }
//                        }
//
//                        @Override
//                        public void onFailure(String failureMsg, int statusCode) {
//
//                        }
//                    });
                }
            }
        });
        RNKitManager.INSTANCE.register(new RNRouterModule(), new RNNetworkModule(), new RNKitImModule()); //, new RNKitSignModule()
    }

    //Arouter
    private void ARouterInit(Application application) {
        if (DevicesUtils.isEnvironment()) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(application);
    }

    //友盟

    private void initUmeng() {
        UmengUtils.setInitialized(false);
        UmengUtils.preInit(this);
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(mobile)) {
            UmengUtils.initUmeng(this, null);
        }

    }


    public boolean isUserAgreeChecked() {
        return UserAgreeChecked;
    }

    public void setUserAgreeChecked(boolean userAgreeChecked) {
        UserAgreeChecked = userAgreeChecked;
//        if (userAgreeChecked) {
//            DEVICES_UUID = SharedPreferencesUtils.getInstance().getUment_String("sp_uuid", "");
//            if (TextUtils.isEmpty(DEVICES_UUID)) {
//                DEVICES_UUID = getUUID(this);
//                NetAttestationUtils.getInstance().setSALT("");
//                SharedPreferencesUtils.getInstance().saveUment("sp_uuid", DEVICES_UUID);
//            }
//        }
    }
}
